package com.gxinyu.needle.login

import android.os.Bundle
import androidx.core.os.bundleOf
import com.alibaba.android.arouter.facade.annotation.Route
import com.gxinyu.needle.BaseFragment
import com.gxinyu.needle.constans.LOGIN_RESULT
import com.gxinyu.needle.constans.RoutePath
import com.gxinyu.needle.createViewModel
import com.gxinyu.needle.databinding.FragmentLoginBinding

/**
 * @author gxinyu
 * @date  2022/5/8
 * @desc 登录页面
 */
@Route(path = RoutePath.LOGIN_HOME)
class LoginFragment : BaseFragment<LoginViewModel, FragmentLoginBinding>() {

    override fun bindViewModel(): LoginViewModel {
        return createViewModel<LoginViewModel>().value
    }

    override fun bindLayout(): FragmentLoginBinding {
        return FragmentLoginBinding.inflate(layoutInflater)
    }

    override fun bindBundle(bundle: Bundle) {
        super.bindBundle(bundle)
        viewModel?.bindBundle(bundle)
    }

    override fun bindObserver() {
        super.bindObserver()
        viewModel?.loginName?.observe(viewLifecycleOwner) {
            binding.tvName.text = it
        }
        viewModel?.loginPwd?.observe(viewLifecycleOwner) {
            binding.tvPwd.text = it
        }

        viewModel?.loginResult?.observe(viewLifecycleOwner) {
            if (it == true) {
                binding.tvLoginState.text = "登录成功"
            } else {
                binding.tvLoginState.text = "登录失败"
            }
        }
    }

    override fun bindListener() {
        super.bindListener()
        binding.btnLogin.setOnClickListener {
            viewModel?.login(viewModel?.loginName?.value, viewModel?.loginPwd?.value)
        }

        binding.btnBack.setOnClickListener {
            onBackPressed()
        }

        binding.btnBackResult.setOnClickListener {
            onBackResult(bundleOf(LOGIN_RESULT to viewModel?.loginResult?.value))
        }
    }
}